package cn.szq.concurrent.thread.countdownlatch;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: ConditionDemo
 * @Description:
 * @Author: szq
 * @Date: 2021-10-25 09:07:45
 */
public class ConditionDemo {

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    void method1() throws InterruptedException {
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getName() + "条件不满足，开始await");
            System.out.println("before await: " + lock.getHoldCount());
            condition.await();
            System.out.println("after await: " + lock.getHoldCount());
            System.out.println(Thread.currentThread().getName() + "条件满足了，开始执行。");
        } finally {
            lock.unlock();
            System.out.println("method1-unlock-after: " + lock.getHoldCount());
        }
    }

    void method2() throws InterruptedException {
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getName() + "需要5秒钟的准备时间。");
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName() + ":准备工作完成，唤醒其他的线程");
            System.out.println("before signal: " + lock.getHoldCount());
            condition.signal();
            System.out.println("after signal: " + lock.getHoldCount());
        } finally {
            lock.unlock();
            System.out.println("method2-unlock-after: " + lock.getHoldCount());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ConditionDemo conditionDemo = new ConditionDemo();
        new Thread(() -> {
            try {
                conditionDemo.method2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        conditionDemo.method1();
    }
}
